<template>
  <!-- 忘记密码表单 -->
  <view class="forget-pwd-form uni-pa-10">
    <uni-forms ref="forgetPwdFormRef" :modelValue="state.form" :rules="state.formRules">
      <uni-forms-item label="手机号" name="phone" required>
        <uni-easyinput v-model="state.form.phone"></uni-easyinput>
      </uni-forms-item>
      <CaptchaComp :phone="state.form.phone" @get-captcha="receiveCaptcha" />
      <uni-forms-item label="密码" name="passwd" required>
        <uni-easyinput v-model="state.form.passwd" type="password"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="确认密码" name="repasswd" required>
        <uni-easyinput v-model="state.form.repasswd" type="password"></uni-easyinput>
      </uni-forms-item>
    </uni-forms>
    <button class="btn-in-login" type="warn" size="mini" @tap="doResetPasswd">重置密码</button>
    <view class="register-txt uni-mt-5">
      <navigator url="/pagesLogin/settings/login">已有账号？去登录</navigator>
    </view>
  </view>
</template>
<script setup lang="ts">
import {ref} from "vue";
import CaptchaComp from './components/captcha.vue'
import type {RegisterType} from "@/types/user";
import {resetPasswd} from "@/services/login";

const forgetPwdFormRef= ref()
const state = ref({
  form: {
    phone: "19877966119",
    code: "",
    passwd: "666666",
    repasswd: "666666"
  } as RegisterType,
  formRules: {
    phone: {
      rules: [
        {required: true, errorMessage: "请输入手机号"}
      ]
    },
    code: {
      rules: [
        {required: true, errorMessage: "请输入验证码"}
      ]
    },
    passwd: {
      rules: [
        {required: true, errorMessage: "请输入密码"},
        {minLength: 3, errorMessage: "最少3位密码"}
      ]
    },
    repasswd: {
      rules: [
        {required: true, errorMessage: "请输入确认密码"},
        {minLength: 3, errorMessage: "最少3位密码"}
      ]
    },
  }
})

const receiveCaptcha = (captcha: string) => {
  console.log("receive captcha component data: ", captcha)
  state.value.form.code = captcha
}

const doResetPasswd = () => {
  forgetPwdFormRef.value.validate().then(() => {
    resetPasswd(state.value.form).then(() => {
      uni.showToast({
        title: "重置成功，请重新登录"
      })
      // 导航到登录页
      uni.navigateTo({
        url: "/pagesLogin/settings/login"
      })
    }).catch(() => {})
  }).catch((err: any) => {
    console.log('表单错误信息：', err);
  })

}
</script>
<style scoped lang="scss">
.forget-pwd-form {
  display: flex;
  flex-direction: column;
  justify-content: center;

}
.btn-in-login {
  width: 100%;
}
.register-txt {
  color: #909399;
  font-size: 12px;
}
.disable-item {
  background-color: #8f939c;
  color: #fff;
}
</style>